package com.tronsis.distribution.fragment.stock;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

import com.lzy.imagepicker.bean.ImageItem;
import com.tronsis.distribution.R;
import com.tronsis.distribution.activity.me.UnPassActivity;
import com.tronsis.distribution.activity.me.order.OrderDetailActivity;
import com.tronsis.distribution.bean.AskBuyBean;
import com.tronsis.distribution.bean.BuyRequestBean;
import com.tronsis.distribution.biz.factory.OrderBizFactory;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.distribution.util.StateUtil;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.MultiItemTypeAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.adapter.recyclerview.wrapper.LoadMoreWrapper;
import com.tronsis.library.fragment.BaseFragment;
import com.tronsis.library.http.ListBean;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.util.DateUtil;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.util.StringUtil;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 进货处理 待审核
 *
 * @author scofield@tronsis.com
 * @date 2019/3/13 15:58
 */
public class StockProcessingFragment extends BaseFragment {

    @BindView(R.id.rv_stock_audit)
    RecyclerView mRvAudit;

    private CommonAdapter<BuyRequestBean> mAdapter;
    private List<BuyRequestBean> mDataList = new ArrayList<>();

    private String mState;
    private int mPage = 1;
    private int mSize = 15;
    private int mTotal;
    private LoadMoreWrapper mLoadMoreWrapper;
    private boolean isInited = false;

    @Override
    protected View onCreateView() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_stock_processing, null);
        ButterKnife.bind(this, view);
        mState = getArguments().getString("state");
        return view;
    }

    @Override
    protected void initData() {
        initRv();
        getAskBuys(mPage, mSize, mState, true);
        isInited = true;
    }

    @Override
    protected void onVisible() {
        super.onVisible();
        if (isInited) {
            getAskBuys(mPage, mSize, mState, true);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if ((requestCode == 100 || requestCode == 200) && resultCode == Activity.RESULT_OK) {
            getAskBuys(mPage, mSize, mState, true);
        }
    }

    private void initRv() {
        mAdapter = new CommonAdapter<BuyRequestBean>(getContext(), mDataList, R.layout.item_stock_processing) {
            @Override
            protected void convert(ViewHolder holder, final BuyRequestBean askBuyBean, final int position) {
                holder.setText(R.id.tv_name, TextUtils.isEmpty(askBuyBean.getBuyerName()) ? "--" : askBuyBean.getBuyerName());
//                holder.setText(R.id.tv_code, getString(R.string.format_upgrade_order_no, askBuyBean.getCode()));
                holder.setText(R.id.tv_createdOn, DateUtil.getDateTimeString(askBuyBean.getStateOn()));
                holder.setText(R.id.tv_total_item, getString(R.string.format_total_item, askBuyBean.getTotalItem()));
                RecyclerView rv = holder.getView(R.id.rv_pay_images);
                if (askBuyBean.getPaymentFid() != null) {
                    setImageRv(askBuyBean, rv);
                }

                if (StringUtil.isEquals(mState, StateUtil.UPGRADE_VERIFY)) {
                    holder.getView(R.id.ll_button).setVisibility(View.VISIBLE);
                } else {
                    holder.getView(R.id.ll_button).setVisibility(View.GONE);
                }
                holder.setOnClickListener(R.id.btn_pass, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        showDialog(askBuyBean.getId());
                    }
                });

                holder.setOnClickListener(R.id.btn_un_pass, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(getContext(), UnPassActivity.class);
                        intent.putExtra("buyId", askBuyBean.getId());
                        startActivityForResult(intent, 100);
                    }
                });
            }

            private void setImageRv(final BuyRequestBean askBuyBean, RecyclerView rv) {
                CommonAdapter imageAdapter = new CommonAdapter<ImageItem>(mContext, CommonUtil.getSplitImage(askBuyBean.getPaymentFid()), R.layout.item_grid_image_view) {
                    @Override
                    protected void convert(final ViewHolder holder, final ImageItem imageItem, final int position) {
                        holder.setImageByUrl(mContext, R.id.iv_item, imageItem.url);
                    }
                };
                rv.setLayoutManager(new GridLayoutManager(mContext, 3, LinearLayoutManager.VERTICAL, false) {
                    @Override
                    public boolean canScrollVertically() {
                        return false;
                    }
                });
                rv.setAdapter(imageAdapter);
            }
        };

        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
//                Intent intent = new Intent(mContext, StockProcessingDetailActivity.class);
//                startActivity(intent);
                Intent intent = new Intent(mContext, OrderDetailActivity.class);
                BuyRequestBean buyRequestBean = mDataList.get(position);
                AskBuyBean askBuyBean = new AskBuyBean();
                askBuyBean.setId(buyRequestBean.getId());
                askBuyBean.setState(buyRequestBean.getState());
                askBuyBean.setCouponId(buyRequestBean.getCouponId());
                askBuyBean.setCouponCoverFid(buyRequestBean.getCouponCoverFid());
                intent.putExtra("AskBuyBean", askBuyBean);
                intent.setType("processing");
                startActivity(intent);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        mLoadMoreWrapper = new LoadMoreWrapper(mAdapter);
        mLoadMoreWrapper.setLoadMoreView(R.layout.rv_load_more);
        mLoadMoreWrapper.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (mDataList.size() % 15 == 0 && mDataList.size() > 0 && mDataList.size() < mTotal) {
                    mPage = (mDataList.size() / 15) + 1;
                    getAskBuys(mPage, mSize, mState, false);
                }
            }
        });

        int height = DisplayUtil.getInstance(getContext()).dp2px(14);
        int color = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration = new RecycleViewDivider(getContext(), MyDecoration.VERTICAL_LIST, height, color);
        mRvAudit.addItemDecoration(decoration);
        mRvAudit.setLayoutManager(new LinearLayoutManager(getContext()));
        mRvAudit.setAdapter(mLoadMoreWrapper);
    }


    private void showDialog(final String buyId) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_confirm_ask_buy, null, false);
        final AlertDialog dialog = new AlertDialog.Builder(getContext()).setView(view).create();

        Button btnOk = view.findViewById(R.id.btn_confirm);
        ImageButton btnClose = view.findViewById(R.id.mbt_close);
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                passAskBuy(buyId);
            }
        });

        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        dialog.show();
    }


    private void getAskBuys(int page, int size, final String state, final boolean isRefresh) {
        if (isRefresh) {
            page = 1;
        }

        try {
            OrderBizFactory.createBiz().getAskBuyList(getActivity(), page, size, state, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    ListBean listBean = (ListBean) data;
                    mTotal = listBean.getTotal();
                    List<BuyRequestBean> list = listBean.getList();
                    if (isRefresh) {
                        mDataList.clear();
                        mDataList.addAll(list);
                    } else {
                        mDataList.addAll(list);
                    }

                    mLoadMoreWrapper.notifyDataSetChanged();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();

                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

    private void passAskBuy(String buyId) {
        try {
            OrderBizFactory.createBiz().askBuyPass(getActivity(), buyId, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    getAskBuys(mPage, mSize, mState, true);
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });

        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }


}
